#!/usr/bin/env bash

set -e

DEFAULT_TITLE="Alarm!"
time="$1"
DEFAULT_MSG=${2:-'\\n!!!'}
CURRENT_UNIX_TIME=$(date +"%s")

function convert_time_to_sec() {
  local target_unix_time
  target_unix_time=$(date -d "$1" +"%s")
  echo $(($target_unix_time - $CURRENT_UNIX_TIME))
}

function convert_sec_to_sec() {
  local date_command_format=$(echo $1 | sed "s/s/ second/g")
  convert_time_to_sec "$date_command_format"
}

function convert_min_to_sec() {
  local date_command_format=$(echo $1 | sed "s/m/ minute/g")
  convert_time_to_sec "$date_command_format"
}

function convert_hour_to_sec() {
  local date_command_format=$(echo $1 | sed "s/h/ hour/g")
  convert_time_to_sec "$date_command_format"
}

function convert_datetime_from_unix_time() {
  date +"%Y/%m/%d %H:%M:%S" -d "@$(($CURRENT_UNIX_TIME + $1))"
}

if [[ $time == *:* ]]; then
  SEC=$(convert_time_to_sec $time)
elif [[ $time == *s ]]; then
  SEC=$(convert_sec_to_sec $time)
elif [[ $time == *m ]]; then
  SEC=$(convert_min_to_sec $time)
elif [[ $time == *h ]]; then
  SEC=$(convert_hour_to_sec $time)
else
  SEC=$time
fi

echo "alert after $SEC sec [$(convert_datetime_from_unix_time "$SEC")]"

nohup bash -c "sleep $SEC && notify-send "$DEFAULT_TITLE" "$DEFAULT_MSG" -u critical" >/dev/null 2>&1 &
